package com.atguigu.yygh.sms.service.impl;

import com.atguigu.yygh.common.utils.HttpUtils;
import com.atguigu.yygh.common.utils.RandomUtil;
import com.atguigu.yygh.sms.service.SmsService;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class SmsServiceImp implements SmsService {

    //注入redis
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean sendCode(String phone) {

        //code不为空,表示发送过
        String code = stringRedisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return true;
        }

        //手机验证码(阿里云官网粘贴)
        String host = "https://smsv2.market.alicloudapi.com";
        String path = "/sms/sendv2";
        String method = "GET";
        String appcode = "6ed876cac1904dbfb0933c658718212b";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        String fourBitRandom = RandomUtil.getFourBitRandom(); //获取4为数的验证码
        querys.put("content", "【智能云】您的验证码是"+fourBitRandom+"。如非本人操作，请忽略本短信");
        querys.put("mobile", phone);


        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            stringRedisTemplate.opsForValue().set(phone,fourBitRandom,10, TimeUnit.DAYS); //将验证码存在redis中10天
            return true;//表示发送成功
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
